"""
通过Queue实现进程间通信
"""

import os
import time
import random

from multiprocessing import (Process, Queue)


def write(q):
    """
    写入数据
    """

    print("进程{pid} 写入数据".format(pid=os.getpid()))
    for value in ['Google', 'Apple']:
        print("将数据（{value}）放到队列中".format(value=value))
        q.put(value)
        time.sleep(random.random())


def read(q):
    """
    读取数据
    """

    print("进程{pid} 读取数据".format(pid=os.getpid()))
    while True:
        value = q.get(True)
        print("从队列中读取的数据为（{value}）".format(value=value))


def run():
    # 父进程创建Queue，并传给各个子进程
    q = Queue()
    pw = Process(target=write, args=(q,))
    pr = Process(target=read, args=(q,))
    # 启动子进程pw进行数据写入
    pw.start()
    # 启动子进程pr进行数据读取
    pr.start()

    # 等待pw结束
    pw.join()
    # pr进程里是死循环，无法等待其结束，只能强行终止
    pr.terminate()


if __name__ == "__main__":
    run()
